--- 模块功能：HTTP功能测试.
-- @author openLuat
-- @module http.testHttp
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.23
require "http"
module(..., package.seeall)

local demo = 5
--注释：
-- demo = 1     演示 form 表单 上传文件 和 键值对
-- demo = 2     演示 form 表单 上传文件
-- demo = 3     演示 HTTPS + 证书
-- demo = 4     演示 重定向
-- demo = 5     演示 下载2M-3M的文件到串口1,115200波特率
-- 演示 form 表单 上传文件
if demo == 1 then -- 演示form 表单提交键值对和上传文件
    sys.taskInit(function()
        while not socket.isReady() do sys.wait(2000) end
        local code, head, body = http.request("POST", "http://io.yyia.top:7777/file/upload", 30000, params, {
            path = rtos.get_version():find("8955") and "/ldata/logo_color.jpg" or "/lua/logo_color.jpg",
            addr = "aaaaaaaaaaaaaaaa"
        }, 4, basic, headers, cert, fnc)
        log.info("http demo code:", code)
        if type(head) == "table" then
            for k, v in pairs(head) do
                log.info("http demo head:", k, v)
            end
        end
        if type(body) == "table" then
            local len = 0
            for k, v in ipairs(body) do
                len = len + #v
            end
            log.info("http demo body:", len)
        else
            log.info("http demo body:", body)
        end
    end)
elseif demo == 2 then -- 演示 form 表单 上传文件
    sys.taskInit(function()
        while not socket.isReady() do sys.wait(2000) end
        local code, head, body = http.request("POST", "http://io.yyia.top:7777/file/upload", 30000, params,
            rtos.get_version():find("8955") and "/ldata/logo_color.jpg" or "/lua/logo_color.jpg",
            4, basic, headers, cert, fnc)
        log.info("http demo code:", code)
        if type(head) == "table" then
            for k, v in pairs(head) do
                log.info("http demo head:", k, v)
            end
        end
        if type(body) == "table" then
            local len = 0
            for k, v in ipairs(body) do
                len = len + #v
            end
            log.info("http demo body:", len)
        else
            log.info("http demo body:", body)
        end
    end)
elseif demo == 3 then -- GET 请求HTTPS + 证书
    sys.taskInit(function()
        while not socket.isReady() do sys.wait(2000) end
        local code, head, body = http.request("GET", "https://www.baidu.com", 30000, nil, nil, nil, nil, nil, {caCert = "ca.crt"})
        log.info("http demo code:", code)
        if type(head) == "table" then
            for k, v in pairs(head) do
                log.info("http demo head:", k, v)
            end
        end
        if type(body) == "table" then
            local len = 0
            for k, v in ipairs(body) do
                len = len + #v
            end
            log.info("http demo body:", len)
        else
            log.info("http demo body:", body)
        end
    end)
elseif demo == 4 then
    sys.taskInit(function()
        while not socket.isReady() do sys.wait(2000) end
        local code, head, body = http.request("GET", "http://i.baidu.com", 30000, nil, nil, nil, nil, nil, {caCert = "ca.crt"})
        log.info("http demo code:", code)
        if type(head) == "table" then
            for k, v in pairs(head) do
                log.info("http demo head:", k, v)
            end
        end
        if type(body) == "table" then
            local len = 0
            for k, v in ipairs(body) do
                len = len + #v
            end
            log.info("http demo body:", len)
        else
            log.info("http demo body:", body)
        end
    end)
elseif demo == 5 then
    local u1 = uart.new(1, 115200)
    sys.taskInit(function()
        while not socket.isReady() do sys.wait(2000) end
        local code, head, body = http.request("GET", "http://io.yyia.top:7777/shared/down.pdf", 30000, params, nil, 4, basic, headers, cert, function(msg)
            u1:send(msg)
        end)
        log.info("http demo code:", code)
        if type(head) == "table" then
            for k, v in pairs(head) do
                log.info("http demo head:", k, v)
            end
        end
    end)
end

--http.request("GET","https://www.baidu.com",{caCert="ca.crt"},nil,nil,nil,cbFnc)
--http.request("GET","www.lua.org",nil,nil,nil,30000,cbFncFile,"download.bin")
--http.request("GET","http://www.lua.org",nil,nil,nil,30000,cbFnc)
--http.request("GET","www.lua.org/about.html",nil,nil,nil,30000,cbFnc)
--http.request("GET","www.lua.org:80/about.html",nil,nil,nil,30000,cbFnc)
--http.request("POST","www.iciba.com",nil,nil,"Luat",30000,cbFnc)
--http.request("POST","36.7.87.100:6500",nil,{head1="value1"},{[1]="begin\r\n",[2]={file="/lua/http.lua"},[3]="end\r\n"},30000,cbFnc)
--http.request("POST","http://lq946.ngrok.xiaomiqiu.cn/",nil,nil,{[1]="begin\r\n",[2]={file_base64="/lua/http.lua"},[3]="end\r\n"},30000,cbFnc)
--如下示例代码是利用文件流模式，上传录音文件的demo，使用的URL是随意编造的
--[[
http.request("POST","www.test.com/postTest?imei=1&iccid=2",nil,
{['Content-Type']="application/octet-stream",['Connection']="keep-alive"},
{[1]={['file']="/RecDir/rec001"}},
30000,cbFnc)
]]
--如下示例代码是利用x-www-form-urlencoded模式，上传3个参数，通知openluat的sms平台发送短信
--[[
function urlencodeTab(params)
local msg = {}
for k, v in pairs(params) do
table.insert(msg, string.urlEncode(k) .. '=' .. string.urlEncode(v))
table.insert(msg, '&')
end
table.remove(msg)
return table.concat(msg)
end

http.request("POST","http://api.openluat.com/sms/send",nil,
{
["Authorization]"="Basic jffdsfdsfdsfdsfjakljfdoiuweonlkdsjdsjapodaskdsf",
["Content-Type"]="application/x-www-form-urlencoded",
},
urlencodeTab({content="您的煤气检测处于报警状态，请及时通风处理！", phone="13512345678", sign="短信发送方"}),
30000,cbFnc)
]]
--如下示例代码是利用multipart/form-data模式，上传2参数和1个照片文件
--[[
local function postMultipartFormData(url,cert,params,timeout,cbFnc,rcvFileName)
local boundary,body,k,v,kk,vv = "--------------------------"..os.time()..rtos.tick(),{}

for k,v in pairs(params) do
if k=="texts" then
local bodyText = ""
for kk,vv in pairs(v) do
bodyText = bodyText.."--"..boundary.."\r\nContent-Disposition: form-data; name=\""..kk.."\"\r\n\r\n"..vv.."\r\n"
end
body[#body+1] = bodyText
elseif k=="files" then
local contentType =
{
jpg = "image/jpeg",
jpeg = "image/jpeg",
png = "image/png",
}
for kk,vv in pairs(v) do
print(kk,vv)
body[#body+1] = "--"..boundary.."\r\nContent-Disposition: form-data; name=\""..kk.."\"; filename=\""..kk.."\"\r\nContent-Type: "..contentType[vv:match("%.(%w+)$")].."\r\n\r\n"
body[#body+1] = {file = vv}
body[#body+1] = "\r\n"
end
end
end
body[#body+1] = "--"..boundary.."--\r\n"

http.request(
"POST",
url,
cert,
{
["Content-Type"] = "multipart/form-data; boundary="..boundary,
["Connection"] = "keep-alive"
},
body,
timeout,
cbFnc,
rcvFileName
)
end

postMultipartFormData(
"1.202.80.121:4567/api/uploadimage",
nil,
{
texts =
{
["imei"] = "862991234567890",
["time"] = "20180802180345"
},

files =
{
["logo_color.jpg"] = "/ldata/logo_color.jpg"
}
},
60000,
cbFnc
)
]]
-- 打印剩余内存
sys.timerLoopStart(function()
    log.info("打印占用的内存:", _G.collectgarbage("count"))-- 打印占用的RAM
    log.info("打印可用的空间", rtos.get_fs_free_size())-- 打印剩余FALSH，单位Byte
end, 10000)
